package contact

import (
	"center/db"
	"common/uuid"
	"common/version"
	"common/ws_contact"
	"context"
	"errors"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
)

//接收处理node发过来的消息

type Endpoint struct {
	db     *db.CenterDB
	logger *zap.Logger
}

func NewEndpoint(db *db.CenterDB, log *zap.Logger) *Endpoint {
	return &Endpoint{db: db, logger: log}
}

// CheckIn 节点心跳信息
func (ed *Endpoint) CheckIn(ctx context.Context, req ws_contact.CheckInRequest) (res ws_contact.CheckInResponse, err error) {
	defer func() { err = Error.Wrap(err) }()
	res.Status = true
	res.InterVal = 10 //todo 从配置中读

	validate := validator.New()
	err = validate.Struct(req)
	ed.logger.Debug("checkin", zap.String("dev id", req.DevId), zap.String("ip", req.Ip))

	if err != nil {
		return
	}
	nid, err := uuid.FromString(req.NodeId)
	if err != nil {
		err = errors.New("Heartbeat nodeId error")
		return
	}
	ver, err := version.FromString(req.Version)
	if err != nil {
		return
	}

	err = ed.db.AddOnUpdateNode(ctx, &db.AddNodeParam{
		ID:      nid,
		DevId:   req.DevId,
		Ip:      req.Ip,
		Ipv6:    req.Ipv6,
		Nat:     req.Nat,
		Port:    req.Port,
		Region:  req.Region,
		Version: ver,
	})
	return
}

func (ed *Endpoint) Report(ctx context.Context, req ws_contact.ReportRequest) (err error) {
	defer func() { err = Error.Wrap(err) }()
	nid, err := uuid.FromString(req.NodeId)
	if err != nil {
		err = errors.New(("Report nodeid error"))
		return
	}
	err = ed.db.UpdateFreeSpace(ctx, &db.UpdateNodeInfoParam{
		ID:         nid,
		FreeSpace:  req.FreeDisk,
		TotalSpace: req.TotalDisk,
		DataSpace:  req.DataTotal,
	})
	return nil
}
